package com.ruoyi.oa.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.oa.config.JinZhiConfig;
import com.ruoyi.oa.enums.JinZhiApiEnum;
import com.ruoyi.oa.invoker.JinZhiOpenApiInvoker;
import com.ruoyi.oa.invoker.pojo.dto.JinZhiCallRequest;
import com.ruoyi.oa.invoker.pojo.vo.JinZhiResponseVO;
import com.ruoyi.oa.vo.OaOrgVO;
import com.ruoyi.system.mapper.SysDeptMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SyncOaDeptDataService {

    @Resource
    private JinZhiOpenApiInvoker jinZhiOpenApiInvoker;

    @Resource
    private SysDeptMapper sysDeptMapper;

    @Resource
    private JinZhiConfig jinZhiConfig;

    /**
     * 同步部门数据
     */
    public void syncDept(){
        // 获取oa中的部门数据
        List<OaOrgVO> oaOrgVOList = this.getOaDeptList();
        if(CollUtil.isEmpty(oaOrgVOList)){
            log.info("oaOrgVOList is empty");
            return;
        }
        // 类型转换 oa部门数据-》sysDept数据
        List<SysDept> oaSysDeptList = oaOrgVOList.stream().map(oaOrgVO -> {
            SysDept sysDept = new SysDept();
            sysDept.setDeptId(oaOrgVO.getJgbm());
            sysDept.setDeptName(oaOrgVO.getJgmc());
            sysDept.setOrderNum(oaOrgVO.getPx());
            if(jinZhiConfig.getOaDgyDeptId().equals(oaOrgVO.getLsjg())){
                sysDept.setParentId(jinZhiConfig.getDgyDeptId());
            }
            // 祖级列表
            sysDept.setAncestors(jinZhiConfig.getDgyDeptId()+","+oaOrgVO.getJgbm());

            return sysDept;
        }).collect(Collectors.toList());

        // 查询现有部门
        SysDept dept = new SysDept();
        List<SysDept> sysDeptList = sysDeptMapper.selectDeptList(dept);

        // 更新或者新增部门信息(若原有数据中有ID则为更新，否则为新增)
        List<SysDept> updateDeptList = new ArrayList<>();
        List<SysDept> insertDeptList = new ArrayList<>();
        for (SysDept newDept : oaSysDeptList) {
            boolean exists = false;
            // 检查是否需要更新
            if(CollUtil.isNotEmpty(sysDeptList)){
                exists = sysDeptList.stream()
                        .anyMatch(existingDept -> existingDept.getDeptId().equals(newDept.getDeptId()));
            }
            if (exists) {
                // 更新部门信息
                updateDeptList.add(newDept);
            }else{
                // 新增部门信息
                insertDeptList.add(newDept);
            }
        }
        // 新增部门信息
        if(CollUtil.isNotEmpty(insertDeptList)){
            int insertRet = sysDeptMapper.insertDeptBatch(insertDeptList);
            log.info("insert dept list success,insertRet:{}", insertRet);
        }

        // 更新部门信息
        if(CollUtil.isNotEmpty(updateDeptList)){
            int updateRet = sysDeptMapper.updateDeptBatch(updateDeptList);
            log.info("update dept list success,updateRet:{}", updateRet);
        }
        return;
    }

    /**
     * 获取oa的部门数据
     */
    private List<OaOrgVO> getOaDeptList(){
        // http请求获取oa的机构数据
        JinZhiCallRequest jinZhiCallRequest = new JinZhiCallRequest();
        jinZhiCallRequest.setJinZhiApiEnum(JinZhiApiEnum.SCHOOL_ORG);
        JinZhiResponseVO jinZhiResponseVO = jinZhiOpenApiInvoker.invoke(jinZhiCallRequest);

        // 获取到的机构数据
        List<OaOrgVO> oaOrgVOList = new ArrayList<>();
        Object orgJsonData = jinZhiResponseVO.getValue();
        if(orgJsonData == null){
            return oaOrgVOList;
        }
        // 使用 Jackson 进行转换
        try {
            // 创建 ObjectMapper 实例
            ObjectMapper objectMapper = new ObjectMapper();
            // 使用 TypeReference 指定要转换的目标类型
            TypeReference<List<OaOrgVO>> typeReference = new TypeReference<List<OaOrgVO>>() {};;
            // 将 Object 转换为 List
            oaOrgVOList = objectMapper.readValue(JSONUtil.toJsonStr(orgJsonData), typeReference);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new RuntimeException(e);
        }
        log.info("oaOrgVOList:{}", oaOrgVOList);
       return oaOrgVOList;
    }


}
